package myadmin.jtthink.com.Filters;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import myadmin.jtthink.com.Mapper.RUserMapper;
import myadmin.jtthink.com.Models.RUserModel;
import myadmin.jtthink.com.MyServices.RUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class UserFilter extends OncePerRequestFilter {
    @Autowired
    RUserMapper rUserMapper;
    @Autowired
    RUserService rUserService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        this.setCros(request,response);
        if(request.getHeader("user_id")==null || request.getHeader("user_name")==null){
            filterChain.doFilter(request,response);
            return;
        }
        QueryWrapper<RUserModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",request.getHeader("user_id"))
                .eq("user_name",request.getHeader("user_name"))
                .eq("status",1);
        RUserModel rUserModel = rUserMapper.selectOne(queryWrapper);
        if(rUserModel == null){
            filterChain.doFilter(request,response);
            return ;
        }
        UserDetails userDetails = rUserService.loadUserByUsername(rUserModel.getUserName());

        SecurityContextHolder.getContext()
                .setAuthentication(new UsernamePasswordAuthenticationToken(
                        userDetails,null,
                        userDetails.getAuthorities()));


        filterChain.doFilter(request,response);
    }

    private void setCros(HttpServletRequest request,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");//* or origin as u prefer
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization");
        if (request.getMethod().equals("OPTIONS"))
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
